package com.kyivmohyla.kma2.dao;

import com.kyivmohyla.kma2.dao.mapper.StateRowMapper;
import com.kyivmohyla.kma2.model.State;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

public class StateDaoJdbc extends JdbcDaoSupport implements StateDao {

    @Override
    public State getById(int id) throws DataAccessException {
        return getJdbcTemplate().queryForObject(
                "SELECT state_id, NAME FROM state WHERE state_id = ?",
                new Object[]{id}, new StateRowMapper());
    }

    @Override
    public List<State> getAll() throws DataAccessException {
        return getJdbcTemplate().query(
                "SELECT state.state_id, state.name FROM state ORDER BY state_id",
                new StateRowMapper());
    }

    @Override
    public void create(State state) throws DataAccessException {
        getJdbcTemplate()
                .update("INSERT INTO state (state_id, NAME) VALUES (state_seq.NEXTVAL, ?)",
                        state.getName());
    }

    @Override
    public void update(State state) throws DataAccessException {
        getJdbcTemplate().update(
                "UPDATE state SET NAME = ? WHERE state_id = ?",
                state.getName(), state.getStateId());
    }

    @Override
    public void delete(State state) throws DataAccessException {
        getJdbcTemplate().update("DELETE FROM state WHERE state_id = ?",
                state.getStateId());
    }

}
